package com.ruoyi.zhgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.zhgd.util.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhgd.domain.vo.GroutingProcessVo;
import com.ruoyi.zhgd.dto.GroutingResultDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.zhgd.domain.bo.GroutingResultBo;
import com.ruoyi.zhgd.domain.vo.GroutingResultVo;
import com.ruoyi.zhgd.domain.GroutingResult;
import com.ruoyi.zhgd.mapper.GroutingResultMapper;
import com.ruoyi.zhgd.service.IGroutingResultService;

import java.util.*;

/**
 * 压浆结果Service业务层处理
 *
 * @author zyb
 * @date 2023-09-11
 */
@RequiredArgsConstructor
@Service
@DS("sjcj")
public class GroutingResultServiceImpl implements IGroutingResultService {

    private final GroutingResultMapper baseMapper;

    /**
     * 查询压浆结果
     */
    @Override
    public GroutingResultVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询压浆结果列表
     */
    @Override
    public TableDataInfo<GroutingResultVo> queryPageList(GroutingResultBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<GroutingResult> lqw = buildQueryWrapper(bo);
        Page<GroutingResultVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询压浆结果列表
     */
    @Override
    public List<GroutingResultVo> queryList(GroutingResultBo bo) {
        LambdaQueryWrapper<GroutingResult> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<GroutingResult> buildQueryWrapper(GroutingResultBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<GroutingResult> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceNumber()), GroutingResult::getDeviceNumber, bo.getDeviceNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getBeamNumber()), GroutingResult::getBeamNumber, bo.getBeamNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getHoleNumber()), GroutingResult::getHoleNumber, bo.getHoleNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getGroutingMode()), GroutingResult::getGroutingMode, bo.getGroutingMode());
        lqw.eq(bo.getGroutingDate() != null, GroutingResult::getGroutingDate, bo.getGroutingDate());
        lqw.eq(StringUtils.isNotBlank(bo.getMixRatio()), GroutingResult::getMixRatio, bo.getMixRatio());
        lqw.eq(StringUtils.isNotBlank(bo.getWaterCementRatio()), GroutingResult::getWaterCementRatio, bo.getWaterCementRatio());
        lqw.eq(bo.getMixingTime() != null, GroutingResult::getMixingTime, bo.getMixingTime());
        lqw.eq(bo.getStartTime() != null, GroutingResult::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, GroutingResult::getEndTime, bo.getEndTime());
        lqw.eq(bo.getInflowPressure() != null, GroutingResult::getInflowPressure, bo.getInflowPressure());
        lqw.eq(bo.getBackflowPressure() != null, GroutingResult::getBackflowPressure, bo.getBackflowPressure());
        lqw.eq(bo.getHoldingTime() != null, GroutingResult::getHoldingTime, bo.getHoldingTime());
        lqw.eq(bo.getInflowVolume() != null, GroutingResult::getInflowVolume, bo.getInflowVolume());
        lqw.eq(bo.getTheoreticalInflowVolume() != null, GroutingResult::getTheoreticalInflowVolume, bo.getTheoreticalInflowVolume());
        lqw.eq(bo.getVacuumPumpPressure() != null, GroutingResult::getVacuumPumpPressure, bo.getVacuumPumpPressure());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), GroutingResult::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增压浆结果
     */
    @Override
    public Boolean insertByBo(GroutingResultBo bo) {
        GroutingResult add = BeanUtil.toBean(bo, GroutingResult.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改压浆结果
     */
    @Override
    public Boolean updateByBo(GroutingResultBo bo) {
        GroutingResult update = BeanUtil.toBean(bo, GroutingResult.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GroutingResult entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除压浆结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public PageUtils resultList(Page page, Map<String, Object> params) {
        List<Map> resultList = baseMapper.resultList(page, params);
        /**
         * 灌浆判断条件：
         * 1、进浆压力是否在0.5-0.7MPa；
         * 2、保压时间是否在180-300s；
         * 3、水胶比是否在0.26-0.28之间；
         * 4、初始流动速度是否在10-17秒之间；
         */

        return new PageUtils(page.setRecords(resultList));
    }

    @Override
    public List<GroutingResultDto> statisticAnalysis(String linkCode) {
        return baseMapper.statisticAnalysis(linkCode);
    }

    /**
     * 压浆报表明细
     *
     * @param params
     * @return
     */
    @Override
    public List<GroutingResultVo> reportDetail(Map<String, Object> params) {
        if (ObjectUtils.isEmpty(params.get("beamNumber"))) {
            throw new ServiceException("梁号不能为空");
        }
        List<GroutingResultVo> list = baseMapper.reportDetail(params);
        // 处理开始时间和结束时间
        for (GroutingResultVo vo : list) {
            String startTime = vo.getStartTime();
            String endTime = vo.getEndTime();
            if (StringUtils.isNotBlank(startTime)) {
                vo.setStartTime(startTime.substring(11, 16));
            }
            if (StringUtils.isNotBlank(endTime)) {
                vo.setEndTime(endTime.substring(11, 16));
            }
        }
        return list;
    }

    /**
     * 压浆过程数据
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<GroutingProcessVo> processData(GroutingResultBo bo, PageQuery pageQuery) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("主键不能为空");
        }
        QueryWrapper<GroutingResult> wrapper = new QueryWrapper<>();
        wrapper.eq("id", bo.getId());
        GroutingResultVo result = baseMapper.selectVoOne(wrapper);

        GroutingProcessVo vo = new GroutingProcessVo();
        vo.setId(vo.getId());
        vo.setDeviceNumber(result.getDeviceNumber());
        vo.setHoleNumber(result.getHoleNumber());
        vo.setBeamNumber(result.getBeamNumber());

        String processData = baseMapper.processData(bo);
        // 处理过程数据的格式
        List<GroutingProcessVo> list = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(processData)) {
            String[] split = processData.split(";");
            for (String string : split) {
                String[] str = string.split(",");
                vo.setProcessDate(str[0]);
                vo.setEnterPressure(Double.valueOf(str[1]));
                vo.setReturnPressure(Double.valueOf(str[2]));
                vo.setVacuumPressure(Double.valueOf(str[3]));
                vo.setFlow(Double.valueOf(str[4]));
                list.add(vo);
            }
        }
        int fromIndex = (pageQuery.getPageNum()-1)*pageQuery.getPageSize();
        int toIndex = fromIndex + pageQuery.getPageSize();
        if (toIndex > list.size()) {
            toIndex = list.size();
        }
        List<GroutingProcessVo> data = list.subList(fromIndex, toIndex);
        return TableDataInfo.build(data);
    }

    /**
     * echarts折线图
     *
     * @param bo
     * @return
     */
    @Override
    public Map<String, List<String>> processDataEcharts(GroutingResultBo bo) {
        if (ObjectUtils.isEmpty(bo.getId())) {
            throw new ServiceException("主键不能为空");
        }
        String processData = baseMapper.processData(bo);
        List<String> processDateX = new ArrayList<>();
        List<String> enterPressure = new ArrayList<>();
        List<String> returnPressure = new ArrayList<>();
        List<String> vacuumPressure = new ArrayList<>();
        List<String> flow = new ArrayList<>();
        // 处理过程数据的格式
        if (ObjectUtils.isNotEmpty(processData)) {
            String[] split = processData.split(";");
            for (String string : split) {
                String[] str = string.split(",");
                processDateX.add(str[0]);
                enterPressure.add(str[1]);
                returnPressure.add(str[2]);
                vacuumPressure.add(str[3]);
                flow.add(str[4]);
            }
        }
        Map<String, List<String>> map = new HashMap<>();
        map.put("processDateX", processDateX);
        map.put("enterPressure", enterPressure);
        map.put("returnPressure", returnPressure);
        map.put("vacuumPressure", vacuumPressure);
        map.put("flow", flow);
        return map;
    }
}
